<script setup>
import {ref, watch} from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  length: {
    type: Number,
    default: 6
  },
  type: {
    type: String,
    default: 'number'
  }
})
const emit = defineEmits(['update:modelValue'])

const code = ref(props.modelValue || '')
const focus = ref(true)
const isCode = ref(true)

watch(props, newProps => {
  if (newProps.modelValue !== code.value) {
    code.value = newProps.modelValue
  }
})

const codeNumInputFun = e => {
  let val = e.detail.value
  code.value = val
  isCode.value = val.length !== props.length;
  emit('update:modelValue', code.value)
}

const codeNumBlurFun = e => {
  let val = e.detail.value
  focus.value = false
  isCode.value = val.length !== props.length;
}

const codeFocusFun = index => {
  focus.value = true
}
</script>

<template>
  <view class="split-input-container">
    <input class="single-input"
           adjust-position="false"
           auto-blur="true"
           @blur="codeNumBlurFun"
           @input="codeNumInputFun"
           :type="props.type"
           :maxlength="props.length"
           :focus="focus"
           v-model="code" />
    <view class="codeinput">
      <view v-for="(item,index) in props.length"
            :class="{ color1: index === code.length, color2: index !== code.length }"
            :key="index"
            @click="codeFocusFun(index)">
        {{ props.type === 'password' && code[index] ? '*' : code[index] }}
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.split-input-container {
  position: relative;
  .single-input {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    height: 120rpx;
    opacity: 0;
    font-size: 0;
  }
  .codeinput {
    display: flex;
    justify-content: center;
    margin: auto;
    height: 120rpx;
    .color1 {
      background-color: $kaoyan-color-7;
    }
    .color2 {
      background-color: $kaoyan-color-12;
    }
    view {
      flex: 0 0 96rpx;
      width: 96px;
      height: 120rpx;
      line-height: 120rpx;
      font-size: 48rpx;
      font-weight: bold;
      color: #313131;
      text-align: center;
      border-radius: 32rpx;
      &:not(:last-child) {
        margin-right: 16rpx;
      }
    }
  }
}
</style>
